//
//  DCSpeedy.m
//  CDDStoreDemo
//
//  Created by apple on 2017/3/24.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "DCSpeedy.h"
#import "SAMKeychain.h"
#import "GlobalPopUpTool.h"
#import "GeneralPopUp.h"

@implementation DCSpeedy

+(id)dc_chageControlCircularWith:(id)anyControl AndSetCornerRadius:(NSInteger)radius SetBorderWidth:(NSInteger)width SetBorderColor:(UIColor *)borderColor canMasksToBounds:(BOOL)can
{
    CALayer *icon_layer=[anyControl layer];
    [icon_layer setCornerRadius:radius];
    [icon_layer setBorderWidth:width];
    [icon_layer setBorderColor:[borderColor CGColor]];
    [icon_layer setMasksToBounds:can];
    
    return anyControl;
}

+(id)dc_setSomeOneChangeColor:(UILabel *)label SetSelectArray:(NSArray *)arrray SetChangeColor:(UIColor *)color
{
    if (label.text.length == 0) {
        return 0;
    }
    int i;
    NSMutableAttributedString *attributeString  = [[NSMutableAttributedString alloc]initWithString:label.text];
    for (i = 0; i < label.text.length; i ++) {
        NSString *a = [label.text substringWithRange:NSMakeRange(i, 1)];
        NSArray *number = arrray;
        if ([number containsObject:a]) {
            [attributeString setAttributes:@{NSForegroundColorAttributeName:color} range:NSMakeRange(i, 1)];
        }
    }
    label.attributedText = attributeString;
    return label;
}

/**
 改变label文字中某段文字的颜色，大小
 label 传入label（传入前要有文字）
 oneW  从第一个文字开始
 twoW  到最后一个文字结束
 color 颜色
 size 尺寸
 */
+ (void)cy_labelAttributedString:(UILabel*)label firstW:(NSString *)oneW toSecondW:(NSString *)twoW color:(UIColor *)color size:(CGFloat)size{
    // 创建Attributed
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:label.text];
    // 需要改变的第一个文字的位置
    NSUInteger firstLoc = [[noteStr string] rangeOfString:oneW].location;
    // 需要改变的最后一个文字的位置
    NSUInteger secondLoc = [[noteStr string] rangeOfString:twoW].location+1;
    // 需要改变的区间
    NSRange range = NSMakeRange(firstLoc, secondLoc - firstLoc);
    // 改变颜色
    [noteStr addAttribute:NSForegroundColorAttributeName value:color range:range];
    // 改变字体大小及类型
    [noteStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica-BoldOblique" size:size] range:range];
    // 为label添加Attributed
    [label setAttributedText:noteStr];
}

+ (void)cy_setControlDottedLineBorder:(UIView *)anyControl SetBorderWidth:(CGFloat)width SetBorderColor:(UIColor *)borderColor {
    
    CAShapeLayer *border = [CAShapeLayer layer];
    //虚线的颜色
    border.strokeColor = borderColor.CGColor;
    //填充的颜色
    border.fillColor = [UIColor clearColor].CGColor;
    //设置路径
    border.path = [UIBezierPath bezierPathWithRect:anyControl.bounds].CGPath;
    
    border.frame = anyControl.bounds;
    //虚线的宽度
    border.lineWidth = width;
    
    //设置线条的样式
    //    border.lineCap = @"square";
    //虚线的间隔
    border.lineDashPattern = @[@2, @1];
    
    [anyControl.layer addSublayer:border];
}

#pragma mark - 随机数
+ (NSInteger)dc_GetRandomNumber:(NSInteger)StarNum to:(NSInteger)endNum
{
    return (NSInteger)(StarNum + (arc4random() % ((StarNum - endNum )+ 1)));
}


#pragma mark -  根据传入字体大小计算字体宽高
+ (CGSize)dc_calculateTextSizeWithText : (NSString *)text WithTextFont: (NSInteger)textFont WithMaxW : (CGFloat)maxW {
    
    CGFloat textMaxW = maxW;
    CGSize textMaxSize = CGSizeMake(textMaxW, MAXFLOAT);
    
    //    CGSize textSize = [text boundingRectWithSize:textMaxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:textFont]} context:nil].size;
    CGSize textSize = [text boundingRectWithSize:textMaxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font(textFont)} context:nil].size;
    
    return textSize;
}

+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];
    label.text = title;
    label.font = font;
    [label sizeToFit];
    CGFloat width = label.frame.size.width;
    return ceil(width);
}

#pragma mark - 下划线
+ (void)dc_setUpAcrossPartingLineWith:(UIView *)view WithColor:(UIColor *)color
{
    UIView *cellAcrossPartingLine = [[UIView alloc] init];
    cellAcrossPartingLine.backgroundColor = color;
    [view addSubview:cellAcrossPartingLine];
    
    [cellAcrossPartingLine mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(view);
        make.bottom.mas_equalTo(view);
        make.size.mas_equalTo(CGSizeMake(view.cy_width, 1));
        
    }];
    
}
#pragma mark - 竖线
+ (void)dc_setUpLongLineWith:(UIView *)view WithColor:(UIColor *)color WithHightRatio:(CGFloat)ratio;
{
    if (ratio == 0) { // 默认1
        ratio = 1;
    }
    UIView *cellLongLine = [[UIView alloc] init];
    cellLongLine.backgroundColor = color;
    [view addSubview:cellLongLine];
    
    [cellLongLine mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(view);
        make.centerY.mas_equalTo(view);
        make.size.mas_equalTo(CGSizeMake(1, view.cy_height * ratio));
        
    }];
}
#pragma mark - 首行缩进
+ (void)dc_setUpLabel:(UILabel *)label Content:(NSString *)content IndentationFortheFirstLineWith:(CGFloat)emptylen
{
    NSMutableParagraphStyle *paraStyle01 = [[NSMutableParagraphStyle alloc] init];
    paraStyle01.firstLineHeadIndent = emptylen;//首行缩进
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:content attributes:@{NSParagraphStyleAttributeName:paraStyle01}];
    
    label.attributedText = attrText;
}

#pragma mark - 设置圆角
+ (void)dc_setUpBezierPathCircularLayerWithControl:(UIButton *)control size:(CGSize)size;
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:control.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight | UIRectCornerTopLeft |UIRectCornerTopRight cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = control.bounds;
    maskLayer.path = maskPath.CGPath;
    control.layer.mask = maskLayer;
}

#pragma mark - 字符串加星处理
+ (NSString *)dc_encryptionDisplayMessageWith:(NSString *)content WithFirstIndex:(NSInteger)findex
{
    if (findex <= 0) {
        findex = 2;
    }else if (findex + findex > content.length) {
        findex --;
    }
    return [NSString stringWithFormat:@"%@***%@",[content substringToIndex:findex],[content substringFromIndex:content.length - findex]];
}

+(NSString *)UIImageToBase64Str:(UIImage *) image
{
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

#pragma mark - base64图片转编码
+(UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr
{
    NSData *_decodedImageData = [[NSData alloc] initWithBase64EncodedString:_encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
    UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
    return _decodedImage;
}

+ (void)dc_SetUpAlterWithView:(UIViewController *)vc Title:(NSString *)title Message:(NSString *)message Sure:(dispatch_block_t)sureBlock Cancel:(dispatch_block_t)cancelBlock
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    //取消
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
        !cancelBlock ? : cancelBlock();
    }];
    //确定
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        !sureBlock ? : sureBlock();
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    
    [vc presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 系统提示框（只有确定按钮）
+ (void)dc_SetUpSingleAlterWithView:(UIViewController *)vc Title:(NSString *)title Message:(NSString *)message tureTitle:(NSString *)tureTitle Sure:(dispatch_block_t)sureBlock {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    //确定
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:tureTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        !sureBlock ? : sureBlock();
    }];
    [alertController addAction:okAction];
    
    [vc presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 触动
+ (void)dc_callFeedback
{
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle: UIImpactFeedbackStyleHeavy];
        [generator prepare];
        [generator impactOccurred];
    }
    
}
/**
 * 获取14位时间戳（20170515111150）
 *
 */
+ (NSString *)fourteenBitsTimeStamp{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMddHHmmss"];
    
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    return currentTimeString;
}

/**
 * 当前时间（年月日时）
 *
 */
+ (NSString *)currentTimeYearMonthDayHours{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMddHH"];
    
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    return currentTimeString;
}

/**
 * 获取当前日期（2017-05-15）
 *
 */
+ (NSString *)currentDate{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    return currentTimeString;
}

+ (NSString *)generalGetCurrentDate:(NSString *)dateFormat{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:dateFormat];
    
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    return currentTimeString;
}

/**
 * 转换为日期（仅时分）
 *
 */
+ (NSString *)convertStrToHoursAndMinutesTime:(NSString *)timeStr {
    long long time=[timeStr longLongValue];
    
    NSDate *d = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"HH:mm"];
    
    NSString*timeString=[formatter stringFromDate:d];
    
    return timeString;
}


/**
 * 转换为日期（2089-05-15）
 *
 */
+ (NSString *)convertStrToTime:(NSString *)timeStr {
    long long time=[timeStr longLongValue];
    
    NSDate *d = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString*timeString=[formatter stringFromDate:d];
    
    return timeString;
}

/**
 * 转换为年月日 时分
 *
 */
+ (NSString *)convertStrToAllTime:(NSString *)timeStr{
    long long time=[timeStr longLongValue];
    
    NSDate *d = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    
    NSString*timeString=[formatter stringFromDate:d];
    
    return timeString;
}

/**
 * ocr日期格式化
 *
 */
+ (NSString *)ocrDateFormatter:(NSString *)dateStr {
    
    if ([dateStr containsString:@"-"] && dateStr.length == 10) {
        return dateStr;
    }
    
    for(int i=0; i< [dateStr length]; i++) {
        int a = [dateStr characterAtIndex:i];
        if( a > 0x4E00 && a < 0x9FFF){
            return @"";
        }
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyyMMdd"];//yyyy年MM月dd日
    
    NSString *dateString = dateStr;
    
    dateString = [dateString substringToIndex:dateString.length];//误区** 字符串长度必须与formatter长度对应一致 不然date就是nil
    
    NSDate *date = [formatter dateFromString:dateString];
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *dateS = [formatter stringFromDate:date];
    return dateS;
}
#pragma mark - 获取当前屏幕显示的VC
+ (UIViewController *)dc_getCurrentVC
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    
    return currentVC;
}

+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    
    if([rootVC presentedViewController]) {
        // 视图是被presented出来的
        rootVC = [rootVC presentedViewController];
    }
    if([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    }else if([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    }else{
        // 根视图为非导航类
        currentVC = rootVC;
    }
    return currentVC;
}


/**
 
 判断字符串是否为空
 
 @param  aStr 字符串
 
 @return YES  空 NO
 
 */
+ (BOOL)isBlankString:(NSString *)aStr{
    if (!aStr) {
        return YES;
    }
    if ([aStr isKindOfClass:[NSNull class]]){
        return YES;
    }
    if (!aStr.length) {
        return YES;
    }
    if (aStr == nil) {
        return YES;
    }
    
    if (aStr == NULL) {
        
    }
    if ([aStr isEqualToString:@"NULL"]) {
        return YES;
    }
    if ([aStr isEqualToString:@"(null)"]) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
    }
    return NO;
}

/**
 
 判断数组为空
 
 @param arr 数组
 
 @return YES 空 NO
 
 */

+ (BOOL)isBlankArr:(NSArray *)arr{
    
    if (!arr) {
        
        return YES;
        
    }
    if ([arr isKindOfClass:[NSNull class]]) {
        
        return YES;
        
    }
    if (!arr.count) {
        
        return YES;
        
    }
    if (arr == nil) {
        
        return YES;
        
    }
    if (arr == NULL) {
        
        return YES;
        
    }
    if (![arr isKindOfClass:[NSArray class]]) {
        
        return YES;
        
    }
    return NO;
}

/**
 
 判断字典为空
 
 @param  dic 数组
 
 @return YES 空 NO
 
 */

+ (BOOL)isBlankDictionary:(NSDictionary *)dic{
    if (!dic) {
        return YES;
    }
    if ([dic isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    if (!dic.count) {
        return YES;
    }
    if (dic == nil) {
        return YES;
    }
    if (dic == NULL) {
        return YES;
    }
    if (![dic isKindOfClass:[NSDictionary class]]) {
        return YES;
    }
    return NO;
}

//阿帕项目需要
#pragma mark - base64加密
+ (NSString *) base64:(NSString *) input
{
    NSData * data = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    data = [GTMBase64 encodeData:data];
    NSString * output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return output;
}

// 普通的获取UUID的方法
+ (NSString *)getUUID {
    NSString *appName=[[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey];
    NSString *strApplicationUUID =  [SAMKeychain passwordForService:appName account:@"Shipper"];
    if (strApplicationUUID == nil)
    {
        strApplicationUUID  = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        NSError *error = nil;
        SAMKeychainQuery *query = [[SAMKeychainQuery alloc] init];
        query.service = appName;
        query.account = @"Shipper";
        query.password = strApplicationUUID;
        query.synchronizationMode = SAMKeychainQuerySynchronizationModeNo;
        [query save:&error];
        
    }
    return strApplicationUUID;
}
+ (NSString *)getCurrentTimesString{
    
    NSMutableString *mutStr = [NSMutableString stringWithString:[DCSpeedy getCurrentTimes]];
    NSRange range = {0,mutStr.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range1 = {0,mutStr.length};
    //去掉字符串中的:
    [mutStr replaceOccurrencesOfString:@":" withString:@"" options:NSLiteralSearch range:range1];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的-
    [mutStr replaceOccurrencesOfString:@"-" withString:@"" options:NSLiteralSearch range:range2];
    //    DLog(@"=========== %@",mutStr);
    return mutStr;
}
+(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
//    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}

/**
 服务器返回中间带T的日期格式转换
 */
+ (NSString *) timeChange:(NSString *)string {
    
    //带有T和Z的时间格式，是前端没有处理包含时区的，强转后少了8个小时，date是又少了8个小时，所有要加16个小时。
    
    NSString *str =[string stringByReplacingOccurrencesOfString:@"T"withString:@" "];
    
    NSString *sss =[str substringToIndex:19];
    
    //    NSString *str1 =[str stringByReplacingOccurrencesOfString:@".000Z" withString:@""];
    
    NSDateFormatter *dateFromatter = [[NSDateFormatter alloc] init];
    
    [dateFromatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [dateFromatter setTimeZone:timeZone];
    
    NSDate *date = [dateFromatter dateFromString:sss];
    
    NSDate *newdate = [[NSDate date] initWithTimeInterval:8 * 60 * 60 sinceDate:date];//
    
    NSDate *newdate1 = [[NSDate date] initWithTimeInterval:8 * 60 * 60 sinceDate:newdate];
    
    NSString *newstr =[NSString stringWithFormat:@"%@",newdate1];
    
    return newstr;
    
}

/**
 0 驾驶证
 1 从业资格证
 2 身份证正面
 3 身份证反面
 4 司机照
 5 行驶证
 6 道路运输证
 7 车头正面照
 8 挂车行驶证
 9 挂车运营证
 10 营业执照
 11 手持身份证
 12 挂车照片
 13 道路经营许可证
 14 车辆照
 */
+ (NSInteger)judgeUploadImageType:(NSString *)btnTitle {
    //    [women containsString:@"bitch"]
    if ([btnTitle containsString:@"驾驶证"]) {
        return 0;
    } else if ([btnTitle containsString:@"从业资格证"]) {
        return 1;
    } else if ([btnTitle containsString:@"身份证正面"]) {
        return 2;
    } else if ([btnTitle containsString:@"身份证反面"]) {
        return 3;
    } else if ([btnTitle containsString:@"司机照"]) {
        return 4;
    } else if ([btnTitle containsString:@"车辆行驶证"]) {
        return 5;
    } else if ([btnTitle containsString:@"车辆道路运输证"]) {
        return 6;
    } else if ([btnTitle containsString:@"车头"]) {
        return 7;
    } else if ([btnTitle containsString:@"挂车行驶证"]) {
        return 8;
    } else if ([btnTitle containsString:@"挂车运营证"] || [btnTitle containsString:@"挂车道路运输"]) {
        return 9;
    } else if ([btnTitle containsString:@"营业执照"] || [btnTitle containsString:@"统一社会信用代码"]) {
        return 10;
    } else if ([btnTitle containsString:@"手持身份证"]) {
        return 11;
    } else if ([btnTitle containsString:@"挂车照"]) {
        return 12;
    } else if ([btnTitle containsString:@"道路经营"]) {
        return 13;
    } else if ([btnTitle containsString:@"车辆照"]) {
        return 14;
    } else if ([btnTitle containsString:@"安全责任险"]) {
        return 15;
    } else if ([btnTitle containsString:@"挂靠协议"]) {
        return 16;
    } else if ([btnTitle containsString:@"车主声明"]) {
        return 17;
    }
    return 0;
}


+ (void)changeNavControllerGradientView:(UIViewController *)viewController andBgColor:(UIImage *)imageColor andTitleColor:(UIColor *)tColor {
    
    if (@available(iOS 13.0, *)) {
        UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
        appearance.backgroundImage = imageColor;
        appearance.shadowColor = UIColor.clearColor;
        appearance.titleTextAttributes = @{NSForegroundColorAttributeName : tColor, NSFontAttributeName : [UIFont boldSystemFontOfSize:17]};
        viewController.navigationController.navigationBar.standardAppearance = appearance;
        viewController.navigationController.navigationBar.scrollEdgeAppearance = appearance;
        
    } else {
        [viewController.navigationController.navigationBar setBackgroundImage:imageColor forBarMetrics:UIBarMetricsDefault];
        [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : tColor, NSFontAttributeName : [UIFont boldSystemFontOfSize:17]}];
    }
    [viewController.navigationController.navigationBar setShadowImage:[UIImage new]];
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (void)removeLocationNotice {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"JPushNotice.plist"];
    
    if ([fileManager fileExistsAtPath:filePath] == YES) {
        //存在
        [fileManager removeItemAtPath:filePath error:nil];
    }
}

///图片加水印
+ (UIImage *)addWatermarkToPicture:(UIImage *)image :(NSString *)dateString :(NSString *)locationString :(NSString *)coordinateString {
    
    // 计算图片的size
    CGSize imageSize = CGSizeMake(image.size.width, image.size.height);
    // 开启图片类型的图形上下文
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    // 绘制图片
    [image drawAtPoint:CGPointZero];
    // 水印的文字
    NSString *date = dateString;
    NSString *location = locationString;
    NSString *coordinate = coordinateString;
    
    // 绘制文字水印
    CGFloat locationW = [self getWidthWithTitle:location font:[UIFont systemFontOfSize:20]];
    [date drawAtPoint:CGPointMake(10, imageSize.height - 150) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:Theme_ColorValue}];
    if (locationW > imageSize.width) {
        [location drawAtPoint:CGPointMake(10, imageSize.height - 100) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:10], NSForegroundColorAttributeName:Theme_ColorValue}];
    } else {
        [location drawAtPoint:CGPointMake(10, imageSize.height - 100) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:Theme_ColorValue}];
    }
    [coordinate drawAtPoint:CGPointMake(10, imageSize.height - 50) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:Theme_ColorValue}];

    
    // 水印的图片
    //    UIImage *logoImage = [UIImage imageNamed:@"FZSDKLib.bundle/companyLogo"];
    // 绘制图片水印
    //    [logoImage drawAtPoint:CGPointMake(imageSize.width - logoImage.size.width - 30, imageSize.height - logoImage.size.height - 30)];
    // 取图片
    image = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图片类型的图形上下文
    UIGraphicsEndImageContext();
    // 保存到相册中
    //    UIImageWriteToSavedPhotosAlbum(image, NULL, NULL, NULL);
    
    return image;
    
}

+ (UIViewController *)getcurrentTopViewController {
    UIViewController *blockViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (blockViewController.presentedViewController) {
        blockViewController = blockViewController.presentedViewController;
    }
    
    if (![blockViewController isKindOfClass:[UITabBarController class]] &&
        ![blockViewController isKindOfClass:[UINavigationController class]]) {
        UIViewController *currentChildVC;
        
        if (blockViewController.childViewControllers.count) {
            currentChildVC = blockViewController.childViewControllers.lastObject;
        }
        
        while (currentChildVC) {
            blockViewController = currentChildVC;
            if ([blockViewController isKindOfClass:[UITabBarController class]]) {
                blockViewController = [(UITabBarController *)blockViewController selectedViewController];
            }
            
            if ([blockViewController isKindOfClass:[UINavigationController class]]) {
                blockViewController = [(UINavigationController *)blockViewController topViewController];
            }
        }
    }
    
    if ([blockViewController isKindOfClass:[UITabBarController class]]) {
        blockViewController = [(UITabBarController *)blockViewController selectedViewController];
    }

    if ([blockViewController isKindOfClass:[UINavigationController class]]) {
        blockViewController = [(UINavigationController *)blockViewController topViewController];
    }
    
    return blockViewController;
}

+ (BOOL)checkProductDate:(NSString *)tempDate {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *date = [dateFormatter dateFromString:tempDate];
    
    // 判断是否大于当前时间
    if ([date earlierDate:[NSDate date]] != date) {
        
        return true;
    } else {
        
        return false;
    }
}

+ (NSInteger)calculateTimeDifference:(NSString *)beforeTime {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    
    NSDate *datenow = [NSDate date];
    
    NSString *currentTimeString = [dateFormatter stringFromDate:datenow];
    
    NSDate *startDate = [dateFormatter dateFromString:currentTimeString];
    NSDate *endDate = [dateFormatter dateFromString:beforeTime];
    
    //利用NSCalendar比较日期的差异
    NSCalendar *calendar = [NSCalendar currentCalendar];
    /**
     * 要比较的时间单位,常用如下,可以同时传：
     *    NSCalendarUnitDay : 天
     *    NSCalendarUnitYear : 年
     *    NSCalendarUnitMonth : 月
     *    NSCalendarUnitHour : 时
     *    NSCalendarUnitMinute : 分
     *    NSCalendarUnitSecond : 秒
     */
    NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
    //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
    
    return delta.day;
}

//判断是否为整形
+ (BOOL)isPureInt:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    int val;
    
    return [scan scanInt:&val] && [scan isAtEnd];
    
}

+ (BOOL)judgeUserIsLogin {
    
    if (TOKEN_ISEMPTY) {
        
        GeneralPopUp *generalPopUp = [[GeneralPopUp alloc] initWithFrame:CGRectMake(0, 0, ScreenW-50, 240)];
        cut(generalPopUp, 5);
        generalPopUp.backgroundColor = [UIColor whiteColor];
        generalPopUp.mainTitle = @"友情提示";
        generalPopUp.subTitle = @"您还没有登录！";
        generalPopUp.handleBtnTitleArray = @[@"取消", @"去登录"];
        [[GlobalPopUpTool sharedInstance] popUpWithView:generalPopUp withViewController:nil withAnimation:YES withCanTapBgCancel:YES];
        generalPopUp.btnActionResultBlock = ^(BOOL isConfirm, NSString * _Nonnull title, NSInteger index) {
            
            [[GlobalPopUpTool sharedInstance] removePopUpView];
            
            if (isConfirm) {
                id isSMSLogin = [UserDefaultUtil valueForKey:IsLoginNeedSMS];
                if ([isSMSLogin isEqual:@"yes"]) {
                    LoginCodeViewController *loginVc = [[LoginCodeViewController alloc] init];
                    XPRootNavigationController *nav = [[XPRootNavigationController alloc] initWithRootViewController:loginVc];
                    nav.modalPresentationStyle = UIModalPresentationFullScreen;
                    [[DCSpeedy dc_getCurrentVC] presentViewController:nav animated:YES completion:nil];

                } else {
                    
                    LoginViewController *loginVc = [[LoginViewController alloc] init];
                    XPRootNavigationController *nav = [[XPRootNavigationController alloc] initWithRootViewController:loginVc];
                    nav.modalPresentationStyle = UIModalPresentationFullScreen;
                    [[DCSpeedy dc_getCurrentVC] presentViewController:nav animated:YES completion:nil];
                }
            }
        };
        
        return NO;
    }
    
    return YES;
}

/**
 十进制转换十六进制
  
 @param decimal 十进制数
 @return 十六进制数
 */
 + (NSString *)getHexByDecimal:(NSInteger)decimal {
    
    NSString *hex =@"";
    NSString *letter;
    NSInteger number;
    for (int i = 0; i<9; i++) {
        
        number = decimal % 16;
        decimal = decimal / 16;
        switch (number) {
                
            case 10:
                letter =@"a"; break;
            case 11:
                letter =@"b"; break;
            case 12:
                letter =@"c"; break;
            case 13:
                letter =@"d"; break;
            case 14:
                letter =@"e"; break;
            case 15:
                letter =@"f"; break;
            default:
                letter = [NSString stringWithFormat:@"%ld", number];
        }
        hex = [letter stringByAppendingString:hex];
        if (decimal == 0) {
            
            break;
        }
    }
    return hex;
}

/// 时间戳 秒
+(NSInteger)getNowTimeSecondTamp{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;

    [formatter setDateStyle:NSDateFormatterMediumStyle];

    [formatter setTimeStyle:NSDateFormatterShortStyle];

    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // 设置想要的格式，hh与HH的区别:分别表示12小时制,24小时制

    //设置时区,这一点对时间的处理有时很重要

    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

    [formatter setTimeZone:timeZone];

    NSDate *datenow = [NSDate date];

    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    NSLog(@"-----%@",timeSp);
    return [datenow timeIntervalSince1970];

}

@end
